package cn.yudao.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Component
public class CustomFilter extends ZuulFilter {

    /**
    * @Title: filterType
    * @Description: 拦截器类型 "pre","post"
    * @Version: 1.0
    * @Date:  2022/7/31 11:10
    * @Parameters:
    * @Return
    */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
    * @Title: filterOrder
    * @Description: 执行优先级
    * @Version: 1.0
    * @Date:  2022/7/31 11:10
    * @Parameters:
    * @Return
    */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
    * @Title: shouldFilter
    * @Description: 是否执行拦截
    * @Version: 1.0
    * @Date:  2022/7/31 11:10
    * @Parameters:
    * @Return
    */
    @Override
    public boolean shouldFilter() {
        /**
        判断是否进入的公共的url
         */
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); // 获取请求体
        String uri = request.getRequestURI();
        if (uri.endsWith("/login") || uri.endsWith("/register") || uri.contains("/static")){
            return false;
        }

        return true;
    }

    /**
    * @Title: run
    * @Description: 拦截的代码
    * @Version: 1.0
    * @Date:  2022/7/31 11:10
    * @Parameters:
    * @Return
    */
    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()){
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("success",false);
            resultMap.put("message","登录检查失败，请稍后再试!");
            response.setContentType("application/json;charset=utf-8");
            String s = JSON.toJSONString(resultMap);
            response.setStatus(402);
            try {
                response.getWriter().print(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
